{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "11BEbhRng15X"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GitHub\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\n",
        "\n",
        "NOTE: User is responsible for checking the content of datasets and the applicable licenses and determining if suitable for the intended use.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell to install dependencies\n",
        "\n",
        "\n",
        "# Install dependencies\n",
        "!pip install wget\n",
        "!apt-get update && apt-get install -y sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install omegaconf\n",
        "\n",
        "BRANCH='main'\n",
        "\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@{BRANCH}#egg=nemo_toolkit[asr]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ne4_FHPaoVyq"
      },
      "outputs": [],
      "source": [
        "# import libraries\n",
        "\n",
        "import glob\n",
        "import json\n",
        "import librosa\n",
        "import numpy as np\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "import os\n",
        "import soundfile as sf\n",
        "import subprocess\n",
        "import tarfile\n",
        "import tqdm\n",
        "import wget\n",
        "import re\n",
        "\n",
        "import torch"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y0fqj-DkEU2y"
      },
      "source": [
        "# Introduction to Canary models\n",
        "Canary is a family of multilingual, multitask speech-to-text models based on the attention encoder-decoder (AED) architecture. All Canary models use a FastConformer encoder and Transformer decoder. The current lineup includes `canary-1b-v2`, `canary-1b`, `canary-1b-flash`, and `canary-180m-flash`.\n",
        "\n",
        "`canary-1b-v2` is the latest and most comprehensive model, supporting speech recognition for 25 European languages, as well as translation between English and these languages (En<->X). It introduces new features such as parallel chunking and full timestamp prediction across all supported languages.\n",
        "\n",
        "`canary-1b-flash` (883M parameters) and canary-180m-flash (182M parameters) are optimized for speed and efficiency. These models support speech recognition in English, German, French, and Spanish, as well as translation between English and German/French/Spanish (in both directions). They also offer output with or without punctuation and capitalization (PnC), and support word-level timestamp prediction for all four languages. The canary-1b-flash model achieves faster and more accurate results than `canary-1b` by increasing the encoder size and reducing the decoder size, improving speed while maintaining comparable model capacity.\n",
        "In this tutorial, we will focus primarily on the Canary-1b-v2 model.\n",
        "Refer to the following resources for more details:\n",
        "\n",
        "🤗[canary-1b-v2](https://huggingface.co/nvidia/canary-1b-v2)\n",
        "\n",
        "🤗[canary-1b](https://huggingface.co/nvidia/canary-1b)\n",
        "\n",
        "🤗[canary-1b-flash](https://huggingface.co/nvidia/canary-1b-flash)\n",
        "\n",
        "🤗[canary-180m-flash](https://huggingface.co/nvidia/canary-180m-flash)\n",
        "\n",
        "[Canary-1B paper](https://arxiv.org/abs/2406.19674)\n",
        "\n",
        "[Canary-1B-flash paper](https://arxiv.org/abs/2503.05931)\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8itHPnZO5ATe"
      },
      "source": [
        "## Components of Canary architecture\n",
        "\n",
        "### Model architecture\n",
        "\n",
        "The input audio is converted into 128-dim log-mel features extracted for 25ms window with a stride of 10ms. The spectrogram features are then processed through the encoder. The decoder conditions on the encoder output and decoder prompt to autoregressively generate one token at a time.\n",
        "\n",
        "<img src=\"images/promptformat.png\" width=\"750\" height=\"400\">\n",
        "\n",
        "### Decoder prompt\n",
        "\n",
        "Decoder prompt is the key to attaining multitask capability with Canary models. Decoder prompt is a sequence of special tokens that define the precise task (language output text, punctuations, timestamps, etc.) to be performed on the input audio.\n",
        "As shown in the figure, the decoder takes a sequence of prompt tokens as input before generating output text. The example prompt sequence corresponds to English speech recognition as the language for input audio and output text is set to English. The format of the decoder prompt is defined by `TEMPLATE[\"user\"][\"template\"]` in the [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py).\n",
        "\n",
        "\n",
        "### Tokenizers\n",
        "<img src=\"images/tokenizer.png\" width=\"600\" height=\"400\">\n",
        "\n",
        "\n",
        "For Canary-1b-v2, we use a unified SentencePiece [tokenizer](https://github.com/NVIDIA/NeMo/blob/main/scripts/tokenizers/process_asr_text_tokenizer.py).\n",
        "\n",
        "For all other Canary models, we use the concatenated [tokenizer](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/tokenizers/canary_tokenizer.py), which combines language-specific SentencePiece tokenizers with shared special tokens. Each language uses a vocabulary of 1024 subword tokens, and these per-language vocabularies are concatenated together as shown in the figure below.\n",
        "\n",
        "In addition to language-specific tokens, Canary uses 1152 tokens to represent special tokens. Special tokens include generic tokens such as `<|startoftranscript|>`, `<|endoftext|>`, `<pad>`, as well as many other task-specific tokens.\n",
        "Listed below is a variety of special tokens that the default tokenizer includes. This should give an idea of various tasks that can be supported with the current tokenizer and prompt formatter.\n",
        "\n",
        "* Task-specific tokens; these provide a control for tasks and output characteristics, such as decoding with or without punctuations and capitalizations (`<|pnc|>` or `<|nopnc|>`), timestamp prediction (`<|timestamp|>` or `<|notimestamp|>`), emotion recognition (`<|emo:undefined|>`, `<|emo:neutral|>`, `<|emo:happy|>`, `<|emo:sad|>`, `<|emo:angry|>`).\n",
        "* Language identity tokens; the default `spl_tokens` tokenizer supports 184 language IDs, including an `<|unklang|>` token. Language identity tokens are used to encode `source_lang`, `target_lang` fields in the manifest.\n",
        "* Integer tokens; timestamp prediction uses integer values, between `0` and `899` to denote frame numbers corresponding to word start and word end.\n",
        "* Speaker ID tokens; although current Canary-flash models are not trained for speaker identity, the default tokenizer includes 16 speaker ID tokens, `<|spk0|> ... <|spk15|>`.\n",
        "* Additional tokens; the default tokenizer incldes 30 additional tokens, `<|spltoken0|> ... <|spltoken29|>`, not assigned to any perform any particular function. The user can use one of these to represent a custom behavior."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PJczuX9PKI8O"
      },
      "source": [
        "\n",
        "# Outline\n",
        "\n",
        "The tutorial is divided into four sections.\n",
        "\n",
        "First, we see how to perform inference using Canary models, specifically speech recognition, translation, and timestamp prediction.\n",
        "\n",
        "Then we learn how to train a Canary model in two ways -- from scratch and from an initial checkpoint. We will train a model for English speech recognition.\n",
        "\n",
        "Next, we look deeper into various use cases for Canary model with detailed guidelines on how to use Canary-style training for various tasks.\n",
        "\n",
        "Finally, we share some practitioner's tips from our experience working with Canary models."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FbYgKwsi3zuH"
      },
      "source": [
        "# Download LibriLight data\n",
        "We download LibriLight data so we can run inference on audio samples. We'll later use the small 1 hour split for training a custom Canary model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yyAZeHHxdwo1"
      },
      "outputs": [],
      "source": [
        "def download_and_prepare_librilight_data(data_dir=\"datasets\"):\n",
        "    if not os.path.exists(data_dir):\n",
        "        os.makedirs(data_dir)\n",
        "\n",
        "    libri_data_dir = os.path.join(data_dir, 'LibriLight')\n",
        "    libri_tgz_file = f'{data_dir}/librispeech_finetuning.tgz'\n",
        "\n",
        "    if not os.path.exists(libri_tgz_file):\n",
        "        url = \"https://dl.fbaipublicfiles.com/librilight/data/librispeech_finetuning.tgz\"\n",
        "        libri_path = wget.download(url, data_dir, bar=None)\n",
        "        print(f\"Dataset downloaded at: {libri_path}\")\n",
        "\n",
        "    if not os.path.exists(libri_data_dir):\n",
        "        tar = tarfile.open(libri_tgz_file)\n",
        "        tar.extractall(path=libri_data_dir)\n",
        "\n",
        "    print(f'LibriLight data is ready at {libri_data_dir}')\n",
        "\n",
        "download_and_prepare_librilight_data()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eq2NmXaJBtHv"
      },
      "source": [
        "# Inference with Canary-1b-v2 model\n",
        "\n",
        "We run inference on a sample audio files, both short and long, to demonstrate the various capabilities supported by the released Canary-1b-v2 checkpoints.\n",
        "\n",
        "Canary inference uses the `trancribe` method of `EncDecMultiTaskModel`.\n",
        "The user can control the task and language for the inference using specific arguments to `transcribe`. These arguments control the prompt token sequence passed as an input to the decoder (decoder prompt is discussed in more detail in the next section).\n",
        "\n",
        "See examples below for using `transcribe` to perform various tasks."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "O1SXLoY_4VXi"
      },
      "outputs": [],
      "source": [
        "from pydub import AudioSegment\n",
        "from IPython.display import Audio, display\n",
        "\n",
        "def listen_to_audio(audio_path, offset=0.0, duration=-1):\n",
        "    audio = AudioSegment.from_file(audio_path)\n",
        "    start_ms = int(offset * 1000)\n",
        "    if duration == -1:\n",
        "        end_ms = -1\n",
        "    else:\n",
        "        end_ms = int((offset+duration) * 1000)\n",
        "\n",
        "    segment = audio[start_ms:end_ms]\n",
        "    audio = Audio(segment.export(format='wav').read())\n",
        "    display(audio)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DQnHNwq1NayC"
      },
      "source": [
        "## Load model\n",
        "\n",
        "Load the model of your choice.\n",
        "\n",
        "We use `canary-1b-v2` in these inference examples.\n",
        "\n",
        "If testing a local checkpoint, use the following code snippet in place of the one below:\n",
        "```\n",
        "canary_model = EncDecMultiTaskModel.restore_from(\n",
        "        restore_path=ckpt_path,\n",
        "        map_location=map_location,\n",
        "    )\n",
        "```\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "gQSiM4RI4cSj"
      },
      "outputs": [],
      "source": [
        "from nemo.collections.asr.models import EncDecMultiTaskModel\n",
        "map_location = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-1b-v2', map_location=map_location)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ijJeUpYj7DEd"
      },
      "source": [
        "## Speech-to-text recognition\n",
        "\n",
        "Here we pass the `source_lang` (language of audio input) and `target_lang` (language of recognized text) as `en`. Thus, this performs english speech recognition.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9DFBI4Ag7NT3"
      },
      "outputs": [],
      "source": [
        "audio_path = \"datasets/LibriLight/librispeech_finetuning/1h/0/clean/3526/175658/3526-175658-0000.flac\"\n",
        "listen_to_audio(audio_path)\n",
        "\n",
        "# To transcribe in a particular language; this example is for English, but will work for each of 25 supported languages\n",
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English, es: Spanish, fr: French, de: German\n",
        "  target_lang='en',\t# should be same as \"source_lang\" for 'asr'\n",
        ")\n",
        "print(\"\\n\\nEnglish speech recognition:\")\n",
        "print(f'  \\\"{transcript[0].text}\\\"')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LufezWfD4Xj0"
      },
      "source": [
        "## Speech-to-text translation\n",
        "\n",
        "Here we pass the `source_lang` (language of audio input) as `en` and `target_lang` (language of transcription text) as `es`. Thus, this performs English to Spanish speech-to-text translation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qo_kC4RA7pkR"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English, es: Spanish, fr: French, de: German\n",
        "  target_lang='es',\t# should be same as \"source_lang\" for 'asr'\n",
        ")\n",
        "print(\"\\n\\nSpeech to text translation form English to Spanish with punctuations and capitalizations:\")\n",
        "print(f'  \\\"{transcript[0].text}\\\"')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Timestamp Generation Workflow\n",
        "\n",
        "Currently timestamps generation for `canary-1b-v2` is done via 3 steps\n",
        "\n",
        "1. The audio is passed through the Canary v2 model, which is an AED (Attention Encoder-Decoder) multi-task model. The output is a token sequence produced by the decoder of the model.\n",
        "\n",
        "2. The same audio is passed through the Multi-lingual Parakeet CTC model. From this model, we obtain the log-probabilities matrix produced by the CTC decoder of the Parakeet model. \n",
        "    This matrix represents the (log) probability of every possible token for each time frame (80ms time windows for the given models).\n",
        "\n",
        "3. Viterbi Decoding: Given the token sequence (from Canary v2) and the log-probability matrix (from multilingual Parakeet CTC), we perform Viterbi Decoding. The goal is to find the most likely sequence of predicted tokens aligned over time frames.\n",
        "\n",
        "<img src=\"images/canary2_timestamps.png\" width=\"1000\" height=\"400\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CG2mE4HP7rw0"
      },
      "source": [
        "\n",
        "## Timestamp prediction\n",
        "\n",
        "Timestamp prediction is supported for all langauges and can be performed with timestamp prediction by passing `timestamps=True` argument."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LXsCFuevmfEm"
      },
      "outputs": [],
      "source": [
        "# To recognize with timestamps\n",
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English or other supported language\n",
        "  target_lang='en',\t# should be same as \"source_lang\" for 'asr'\n",
        "  timestamps=True\n",
        ")\n",
        "print(\"\\n\\nEnglish speech to text recognition with timestamp prediction:\\n\")\n",
        "\n",
        "print(f'Predicted output: \\n\"{transcript[0].text}\\\"')\n",
        "\n",
        "print('\\nSegment level timestamps:')\n",
        "for sample in transcript[0].timestamp['segment']:\n",
        "    segment, start, end = sample['segment'], sample['start'], sample['end']\n",
        "    print(f'{segment}')\n",
        "    print(f'Segment start: {start:.2f}s')\n",
        "    print(f'Segment end: {end:.2f}s\\n')\n",
        "\n",
        "print('\\nWord level timestamps:')\n",
        "for sample in transcript[0].timestamp['word']:\n",
        "    word, start, end = sample['word'], sample['start'], sample['end']\n",
        "    print(f'{word:<15}[{start:.2f}s, {end:.2f}s]')\n",
        "    # listen_to_audio(audio_path, offset=start, duration=(end-start)) # uncomment to listen to word segments"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mo_yDJKGijH8"
      },
      "source": [
        "## Inference with longform input\n",
        "\n",
        "Canary models natively handle inputs up to ~40 seconds. For longer audio, the input is split into 30–40 s chunks (minimizing padding on the final chunk) and processed in parallel.\n",
        "\n",
        "For recordings longer than one hour, processing occurs in consecutive hour‑long segments.\n",
        "\n",
        "Outputs are seamlessly stitched to produce a single, continuous result.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x4JGVDt5AnZz"
      },
      "source": [
        "### Create a longform audio sample\n",
        "\n",
        "\n",
        "As LibriLight does not have a long duration audio, we'll first create one by stitching together all utterances from a story.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nSw6pW3ktC89"
      },
      "outputs": [],
      "source": [
        "# Creating a longform audio sample\n",
        "\n",
        "def get_longform_audio_sample(data_dir=\"datasets\"):\n",
        "    libri_data_dir = os.path.join(data_dir, 'LibriLight')\n",
        "    audio_paths = glob.glob(os.path.join(libri_data_dir, 'librispeech_finetuning/1h/0/clean/3526/175658/3526-175658-*.flac'))\n",
        "    audio_paths.sort() # sort by the utterance IDs\n",
        "    write_path = os.path.join(libri_data_dir, 'longform','-'.join(os.path.basename(audio_paths[0]).split('-')[:2])+'.wav')\n",
        "    os.makedirs(os.path.dirname(write_path), exist_ok=True)\n",
        "    longform_audio_data = []\n",
        "    for audio_path in audio_paths:\n",
        "        data, sr = librosa.load(audio_path, sr=16000)\n",
        "        longform_audio_data.extend(data)\n",
        "    sf.write(write_path, longform_audio_data, sr)\n",
        "    minutes, seconds = divmod(len(longform_audio_data)/sr, 60)\n",
        "    print(f'{int(minutes)} min {int(seconds)} sec audio file saved at {write_path}')\n",
        "    return write_path\n",
        "\n",
        "longform_audio_path = get_longform_audio_sample()\n",
        "listen_to_audio(longform_audio_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RhsrobUmAsUe"
      },
      "source": [
        "### Longform inference without timestamps\n",
        "\n",
        "`.transcribe()` will perform inference on the long audio file `datasets/LibriLight/longform/3526-175658.wav`, which is currently just the one file that we created above. Alternatively you can also pass a path to a manifest file. We will discuss manifest creation in the the next section.."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "0zT_Aiw5Ax6U"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[longform_audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\n",
        "  target_lang='en',\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SfIXyW6vA1mH"
      },
      "outputs": [],
      "source": [
        "def print_sentences_per_item(items):\n",
        "    for i, item in enumerate(items, 1):\n",
        "        text = item.text if hasattr(item, \"text\") else str(item)\n",
        "        sentences = [s.strip() for s in re.split(r'(?<=[.!?])\\s+', text) if s.strip()]\n",
        "        print(f\"--- Audio {i} ---\")\n",
        "        for s in sentences:\n",
        "            print(s if s[-1] in \".!?\" else s + \".\")\n",
        "        print()\n",
        "print_sentences_per_item(transcript)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rw-OQmQ5AvMh"
      },
      "source": [
        "### Longform inference with timestamps\n",
        "\n",
        "We run the same command as above with `timestamps=True`. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "saSBnOJuA34-"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[longform_audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\n",
        "  target_lang='en',\n",
        "  timestamps=True,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qd0cDiibA633"
      },
      "outputs": [],
      "source": [
        "print('\\nWord level timestamps:')\n",
        "for sample in transcript[0].timestamp['word']:\n",
        "    word, start, end = sample['word'], sample['start'], sample['end']\n",
        "    print(f'{word:<15}[{start:.2f}s, {end:.2f}s]')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6c28bgnN9M8g"
      },
      "source": [
        "# Train a Canary model on custom data\n",
        "\n",
        "Now we will see how to train a Canary model on a custom data. Later we discuss how we can incorporate more languages and tasks.\n",
        "\n",
        "In this example we'll see two ways to train a Canary model on a 1 hour split of the LibriLight data:\n",
        "\n",
        "1. A small, 2-layer encoder, 2-layer decoder, version of the model trained from scratch.\n",
        "\n",
        "2. A 180M model initialized from `canary-180m-flash`.\n",
        "\n",
        "Different components needed for training are passed as an yaml config file to the training script.\n",
        "\n",
        "Next, we'll prepare the following components required to set up the training,\n",
        "\n",
        "```\n",
        "model.train_ds.manifest_filepath=$MANIFEST_PATH \\\n",
        "model.tokenizer.langs.en.dir=\"$LANG_TOKENIZER_DIR\" \\\n",
        "model.tokenizer.langs.spl_tokens.dir=\"$SPL_TOKENIZER_DIR\" \\\n",
        "model.prompt_format=\"canary2\" \\\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash', map_location=map_location)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yXAj7KHP2mW7"
      },
      "source": [
        "## Prepare manifest\n",
        "\n",
        "We'll build manifest from 1 hour split of LibriLight data. The manifest file has a dictionary corresponding to each training sample, something like this:\n",
        "```\n",
        "manifest_sample = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": transcript,\n",
        "    \"target_lang\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"pnc\": \"False\"\n",
        "}\n",
        "```\n",
        "\n",
        "The prepared manifest file will be saved at `datasets/LibriLight/train_manifest.json`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p29r_HSxcwYe"
      },
      "outputs": [],
      "source": [
        "def build_manifest(data_root, manifest_path):\n",
        "    transcript_list = glob.glob(os.path.join(data_root, 'LibriLight/librispeech_finetuning/1h/**/*.txt'), recursive=True)\n",
        "    tot_duration = 0\n",
        "    with open(manifest_path, 'w') as fout:\n",
        "        pass # make sure a new file is created\n",
        "    for transcript_path in tqdm.tqdm(transcript_list):\n",
        "        with open(transcript_path, 'r') as fin:\n",
        "            wav_dir = os.path.dirname(transcript_path)\n",
        "            with open(manifest_path, 'a') as fout:\n",
        "                for line in fin:\n",
        "                    # Lines look like this:\n",
        "                    # fileID transcript\n",
        "                    file_id = line.strip().split(' ')[0]\n",
        "                    audio_path = os.path.join(wav_dir, f'{file_id}.flac')\n",
        "\n",
        "                    transcript = ' '.join(line.strip().split(' ')[1:]).lower()\n",
        "                    transcript = transcript.strip()\n",
        "\n",
        "                    duration = librosa.core.get_duration(path=audio_path)\n",
        "                    tot_duration += duration\n",
        "                    # Write the metadata to the manifest\n",
        "                    metadata = {\n",
        "                      \"audio_filepath\": audio_path,\n",
        "                      \"duration\": duration,\n",
        "                      \"text\": transcript,\n",
        "                      \"lang\": \"en\",\n",
        "                      \"target_lang\": \"en\",\n",
        "                      \"source_lang\": \"en\",\n",
        "                      \"pnc\": \"False\"\n",
        "                    }\n",
        "                    json.dump(metadata, fout)\n",
        "                    fout.write('\\n')\n",
        "    print(f'\\n{np.round(tot_duration/3600)} hour audio data ready for training')\n",
        "\n",
        "data_dir = \"datasets\"\n",
        "train_manifest = os.path.join(data_dir, 'LibriLight/train_manifest.json')\n",
        "build_manifest(data_dir, train_manifest)\n",
        "print(f\"LibriLight train manifests created at {train_manifest}.\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "czGyTkb_8gKy"
      },
      "source": [
        "## Build tokenizer\n",
        "\n",
        "\n",
        "As described in the introduction, we now build a tokenizer for special tokens and for English text from the training data.\n",
        "\n",
        "**Note** that you do not need to train a new tokenizer if you are initializing from Canary-flash models for a task and language that the default tokenizers already support. At the end of this tutorial we discuss some cases where you'd want to retrain the tokenizer and reinitialize the token embeddings."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BWJu6aat8l_j"
      },
      "source": [
        "### Build tokenizer for special *tokens*\n",
        "\n",
        "The tokenizer will be saved at `tokenizers/spl_tokens`. See `tokenizers/spl_tokens/tokenizer.vocab` for a 1152-unit vocabulary of tokens."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "BRANCH='r2.5.0'\n",
        "def wget_from_nemo(nemo_script_path, local_dir=\"scripts\"):\n",
        "    os.makedirs(local_dir, exist_ok=True)\n",
        "    script_url = f\"https://raw.githubusercontent.com/NVIDIA/NeMo/refs/heads/{BRANCH}/{nemo_script_path}\"\n",
        "    script_path = os.path.basename(nemo_script_path)\n",
        "    if not os.path.exists(f\"{local_dir}/{script_path}\"):\n",
        "        !wget -P {local_dir}/ {script_url}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "MUMjzfht8ffo"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo(\"scripts/speech_recognition/canary/build_canary_2_special_tokenizer.py\")\n",
        "output_dir = \"tokenizers/spl_tokens\"\n",
        "!mkdir -p {output_dir}\n",
        "!python scripts/build_canary_2_special_tokenizer.py {output_dir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DcfzLk-E9BKO"
      },
      "source": [
        "### Build language-specific tokenizer\n",
        "\n",
        "The tokenizer will be saved at `tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024`. See `tokenizer.vocab` for a 1024-unit vocabulary of tokens."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "Brc_4kJpB0_1"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo('scripts/tokenizers/process_asr_text_tokenizer.py')\n",
        "LANG='en'\n",
        "DATA='libri1h'\n",
        "VOCAB_SIZE=1024\n",
        "OUT_DIR = f\"tokenizers/{LANG}_{DATA}_{VOCAB_SIZE}\"\n",
        "manifest_path = os.path.join(data_dir, 'LibriLight', 'train_manifest.json')\n",
        "train_text_path = os.path.join(data_dir, 'LibriLight', 'train_text.lst')\n",
        "with open(manifest_path, \"r\") as f:\n",
        "    data = [json.loads(line.strip()) for line in f.readlines()]\n",
        "with open(train_text_path, \"w\") as f:\n",
        "    for line in data:\n",
        "        f.write(f\"{line['text']}\\n\")\n",
        "\n",
        "!python scripts/process_asr_text_tokenizer.py \\\n",
        "  --data_file={train_text_path} \\\n",
        "  --vocab_size={VOCAB_SIZE} \\\n",
        "  --data_root={OUT_DIR} \\\n",
        "  --tokenizer=\"spe\" \\\n",
        "  --spe_type=bpe \\\n",
        "  --spe_character_coverage=1.0 \\\n",
        "  --no_lower_case \\\n",
        "  --log\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CSPT1tGK6IAL"
      },
      "source": [
        "## Prompt format\n",
        "\n",
        "Canary-flash decoder generates output text conditioned on audio encoder representations and the decoder prompt. As described in the introduction, Canary-Flash models use [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py), and so we set the `prompt_format` accordingly\n",
        "\n",
        "```\n",
        "model.prompt_format=\"canary2\"\n",
        "```\n",
        "\n",
        "For the samples in our training data the decoder prompt will have the following sequence of special tokens,\n",
        "\n",
        "`<|startofcontext|><|startoftranscript|><|emo:undefined|><|en|><|en|><|nopnc|><|noitn|><|notimestamp|><|nodiarize|>`\n",
        "\n",
        "Note that source language and target language are set to `en` for English speech recognition **without** pnc (`<|nopnc|>`), timestamps (`<|notimestamp|>`), emotion recognition (`<|emo:undefined|>`), or diarization (`<|nodiarize|>`)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lwMu74rsGsUa"
      },
      "source": [
        "## Train Canary model from scratch\n",
        "\n",
        "Now we have all the components needed to train. We download a local copy of the training script and the default config. We pass the data and tokenizers we prepared above.\n",
        "\n",
        "The tokenizers are processed as follows with their language IDs as keys.\n",
        "\n",
        "```\n",
        "model:\n",
        "  tokenizer:\n",
        "    langs:\n",
        "      spl_tokens: # special tokens model\n",
        "        dir: \"tokenizers/spl_tokens\"\n",
        "        type: bpe\n",
        "      en: # English tokenizer\n",
        "        dir: \"tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024\"\n",
        "        type: bpe\n",
        "```\n",
        "\n",
        "We now train a small Canary model with 2 FastConformer encoder layers and 2 Transformer decoder layers."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GIaZLI4tD8qn"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo('examples/asr/speech_multitask/speech_to_text_aed.py')\n",
        "wget_from_nemo('examples/asr/conf/speech_multitask/fast-conformer_aed.yaml', 'config')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XGnQK_U3_W2d"
      },
      "outputs": [],
      "source": [
        "MANIFEST = os.path.join(\"datasets\", \"LibriLight\", 'train_manifest.json')\n",
        "!HYDRA_FULL_ERROR=1 python scripts/speech_to_text_aed.py \\\n",
        "  --config-path=\"../config\" \\\n",
        "  --config-name=\"fast-conformer_aed.yaml\" \\\n",
        "  name=\"canary-small\" \\\n",
        "  model.prompt_format=\"canary2\" \\\n",
        "  model.train_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.validation_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.test_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.tokenizer.langs.en.dir=\"tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024\" \\\n",
        "  model.tokenizer.langs.spl_tokens.dir=\"tokenizers/spl_tokens\" \\\n",
        "  spl_tokens.model_dir=\"tokenizers/spl_tokens\" \\\n",
        "  model.encoder.n_layers=2 \\\n",
        "  model.transf_decoder.config_dict.num_layers=2 \\\n",
        "  exp_manager.exp_dir=\"canary_results\" \\\n",
        "  exp_manager.resume_ignore_no_checkpoint=true \\\n",
        "  trainer.max_steps=10 \\\n",
        "  trainer.log_every_n_steps=1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6F2XDcwwGA7g"
      },
      "source": [
        "## Train Canary model from a Canary flash checkpoint (aka fine-tuning)\n",
        "\n",
        "We will now train a Canary model initialized from the `canary-180m-flash` checkpoint; in effect finetuning the `canary-180m-flash` model. This is the same checkpoint that we used to run sample inference in the previous section.\n",
        "\n",
        "```\n",
        "init_from_pretrained_model: canary-180m-flash\n",
        "```\n",
        "\n",
        "For the sake of simplicity, we will retain the exact same model architecture as `canary-180m-flash`. You can choose to include and exclude certain layers and parameters from the initial checkpoint; we discuss these customizations in the next section."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GXWGI7LyMrd1"
      },
      "source": [
        "### Build config\n",
        "\n",
        "We'll update the base config that we use in the example above and save the new config as `config/canary-180m-flash-finetune`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rD7VXLlnNJD4"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')\n",
        "\n",
        "base_model_cfg = OmegaConf.load(\"config/fast-conformer_aed.yaml\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6Gh1fky8oZ2t"
      },
      "source": [
        "In the training config, we should ensure compatibility with the pre-trained model.\n",
        "\n",
        "1. Set initialization from `canary-180m-flash`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MU1jdmkALyix"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['name'] = 'canary-180m-flash-finetune'\n",
        "base_model_cfg.pop(\"init_from_nemo_model\", None)\n",
        "base_model_cfg['init_from_pretrained_model'] = \"nvidia/canary-180m-flash\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GcDkgzf3MMlk"
      },
      "source": [
        "2. Set path to the tokenizers from the pre-trained model, so as to ensure that the fine-tuning uses a compatible tokenization. The following command reads tokenizers from `canary_model` and saves the files at `canary_flash_tokenizers/{lang}` directories."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8mu5t-Y0GAT5"
      },
      "outputs": [],
      "source": [
        "canary_model.save_tokenizers('./canary_flash_tokenizers/')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "j-Al1IX0NPBG"
      },
      "outputs": [],
      "source": [
        "for lang in os.listdir('canary_flash_tokenizers'):\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang] = {}\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang]['dir'] = os.path.join('canary_flash_tokenizers', lang)\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang]['type'] = 'bpe'\n",
        "base_model_cfg['spl_tokens']['model_dir'] = os.path.join('canary_flash_tokenizers', \"spl_tokens\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-DbxIylkNlIQ"
      },
      "source": [
        "3. Ensure that the prompt format and relevant parameters match."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I6deg7feN6MZ"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['model']['prompt_format'] = canary_model._cfg['prompt_format']\n",
        "base_model_cfg['model']['prompt_defaults'] = canary_model._cfg['prompt_defaults']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PS3LRt3jLt7G"
      },
      "source": [
        "4. Ensure that the model architecture matches."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s4GFt7OGLtZ-"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['model']['model_defaults'] = canary_model._cfg['model_defaults']\n",
        "base_model_cfg['model']['preprocessor'] = canary_model._cfg['preprocessor']\n",
        "base_model_cfg['model']['encoder'] = canary_model._cfg['encoder']\n",
        "base_model_cfg['model']['transf_decoder'] = canary_model._cfg['transf_decoder']\n",
        "base_model_cfg['model']['transf_encoder'] = canary_model._cfg['transf_encoder']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ItNe8gAmPKki"
      },
      "source": [
        "### Launch training\n",
        "Save config and launch training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_g_vdpioPPEV"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.create(base_model_cfg)\n",
        "with open(\"config/canary-180m-flash-finetune.yaml\", \"w\") as f:\n",
        "    OmegaConf.save(cfg, f)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "t1b7vzJwPfWi"
      },
      "outputs": [],
      "source": [
        "MANIFEST = os.path.join(\"datasets\", \"LibriLight\", 'train_manifest.json')\n",
        "!HYDRA_FULL_ERROR=1 python scripts/speech_to_text_aed.py \\\n",
        "  --config-path=\"../config\" \\\n",
        "  --config-name=\"canary-180m-flash-finetune.yaml\" \\\n",
        "  name=\"canary-180m-flash-finetune\" \\\n",
        "  model.train_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.validation_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.test_ds.manifest_filepath={MANIFEST} \\\n",
        "  exp_manager.exp_dir=\"canary_results\" \\\n",
        "  exp_manager.resume_ignore_no_checkpoint=true \\\n",
        "  trainer.max_steps=10 \\\n",
        "  trainer.log_every_n_steps=1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J2EPlZHQbnFe"
      },
      "source": [
        "# Guidance for different implementation scenarios\n",
        "\n",
        "You can use the Canary-style training to develop a model for most speech applications. We saw one generic example of training on custom data from scratch on English speech recognition. Here we discuss how to handle several other scenarios.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F-bOiydXbymG"
      },
      "source": [
        "## 1. Speech-to-text recognition and translation\n",
        "\n",
        "When creating the manifest, make sure to pass the appropriate `source_lang` and `target_lang` tokens for each data point.\n",
        "\n",
        "You'll need language-specific tokenizers for each language. You can build the tokenizer as we saw in the previous section.\n",
        "\n",
        "The default `spl_tokens` tokenizer, supports 183 language IDs. If you want to use a language not currently represented, you can rebuild the tokenizer with a new set of `spl_tokens` that includes your language of choice.\n",
        "\n",
        "Finally, in the config add paths to different tokenizers with their language IDs as keys.\n",
        "\n",
        "```\n",
        "model:\n",
        "  tokenizer:\n",
        "    langs:\n",
        "      spl_tokens: # special tokens model\n",
        "        dir: \"tokenizers/spl_tokens\"\n",
        "        type: bpe\n",
        "      en: # English tokenizer (example, replace with whichever language you would like or add tokenizers to add tokenizer for additional languages)\n",
        "        dir: \"tokenizers/spe_bpe_v1024_en\"\n",
        "        type: bpe\n",
        "      de: # German tokenizer (example, replace with whichever language you would like or add tokenizers to add tokenizer for additional languages)\n",
        "        dir: \"tokenizers/spe_bpe_v1024_en\"\n",
        "        type: bpe\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xa1Xg28Mb39_"
      },
      "source": [
        "## 2. Training on a new task: A case of decoding with context\n",
        "\n",
        "This is an example of a capability that is already supported by the current [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) as well as the tokenizer model.\n",
        "\n",
        "```\n",
        "\"decodercontext\": Modality.Text\n",
        "```\n",
        "\n",
        "During training, you will pass an additional `decodercontext` argument to the samples in the manifest.\n",
        "```\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": transcript,\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"decodercontext\": decoder_context,\n",
        "}\n",
        "```\n",
        "\n",
        "For example, the `decodercontext` can represent past context or certain keywords or topic of the spoken content. The current implementation assumes that `decodercontext` and the output transcript have the same language."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dXVsHDkIb9mS"
      },
      "source": [
        "## 3. Training on a new task: A case of timestamp prediction\n",
        "\n",
        "Canary-Flash models support timestamp prediction. Here, we include how the manifest, prompt formatter, special tokens, and tokenizer functions were modified to add timestamps support for the Canary model.\n",
        "\n",
        "Canary-Flash interleaves word-level timestamps as frame numbers before and after the word. These the frame numbers correspond to the start and end of a word segment. Such \"interleaving\" patterns might be relavant for other tasks as well such as multi-speaker recognition, where you want to interleave speaker ID tokens before appropriate chunks of text tokens spoken by that speaker.\n",
        "\n",
        "Below, we show how a sample in manifest changes with and without timestamps:\n",
        "\n",
        "```\n",
        "# without timestamps\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": \"it's almost beyond conjecture\",\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"timestamp\": \"no\",\n",
        "}\n",
        "```\n",
        "\n",
        "```\n",
        "# with timestamps\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": \"<|3|> it's <|7|> <|8|> almost <|9|> <|14|> beyond <|20|> <|20|> conjecture <|28|>\",\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"timestamp\": \"yes\",\n",
        "}\n",
        "```\n",
        "\n",
        "In order to support this functionality, the [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) should have the relevant slot value and the default values:\n",
        "\n",
        "```\n",
        "# Should we predict timestamps?\n",
        "\"timestamp\": Modality.TextLiteral(\n",
        "    \"yes\",\n",
        "    \"no\",\n",
        "    \"true\",\n",
        "    \"True\",\n",
        "    \"false\",\n",
        "    \"False\",\n",
        "    \"1\",\n",
        "    \"0\",\n",
        "    \"timestamp\",\n",
        "    \"notimestamp\",\n",
        "    \"<|timestamp|>\",\n",
        "    \"<|notimestamp|>\",\n",
        "),\n",
        "```\n",
        "\n",
        "The default can be set as `<|notimestamp|>`:\n",
        "```\n",
        "optional_slots = {\n",
        "    \"decodercontext\": \"\",\n",
        "    \"emotion\": \"<|emo:undefined|>\",\n",
        "    \"itn\": \"<|noitn|>\",\n",
        "    \"timestamp\": \"<|notimestamp|>\",\n",
        "    \"diarize\": \"<|nodiarize|>\",\n",
        "    \"pnc\": \"<|pnc|>\",  \n",
        "}\n",
        "```\n",
        "\n",
        "Additionally we need tokens to support these additional task-related tokens, `<|timestamp|>`, `<|notimestamp|>`, and integer tokens to encode frame indices.\n",
        "We add 900 integers to the list special tokens along with task-related tokens and rebuild the tokenizer as previously discussed.\n",
        "\n",
        "Now the transcript is a mix of tokens from `spl_tokens` tokenizer (frame indices) and tokens from a language-specific tokenizer.\n",
        "The [canary_tokenizer](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/tokenizers/canary_tokenizer.py) handles this by adding a modified `_text_to_ids` method.\n",
        "\n",
        "\n",
        "```\n",
        "def _text_to_ids_maybe_with_timestamps(self, text_no_eos, lang_id) -> list[int]:\n",
        "    time_pattern = re.compile(r\"<\\|\\d+\\|>\")\n",
        "    time_text = \"\".join(time_pattern.findall(text_no_eos))\n",
        "    has_timestamp = bool(time_text)\n",
        "    if not has_timestamp:\n",
        "        return super().text_to_ids(text_no_eos, lang_id)\n",
        "    else:\n",
        "        text_without_timestamps = time_pattern.sub(\"\", text_no_eos).strip()\n",
        "        return self._text_with_timestamps_to_ids(text_without_timestamps, time_text, lang_id)\n",
        "\n",
        "```\n",
        "\n",
        "Once these changes are in place, you should be able to train the model on data with word-level timestamps."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ejjCj3XfcIpR"
      },
      "source": [
        "## 4. Training on a new task: A case of speech summarization\n",
        "\n",
        "Speech summarization is an example of completely new task, meaning, neither the prompt format nor the default special tokens have an explicit support for this task.\n",
        "\n",
        "You will start with modifying [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) or even writing your own custom prompt formatter. [This tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Prompt%20Formatter%20Tutorial.ipynb) has useful references on modifying and building custom prompt formatter.\n",
        "\n",
        "\n",
        "One possible way to modify the existing promp format is to add an optional `\"summarize\"` key whose default value is `false`:\n",
        "```\n",
        "# should we summarize?\n",
        "\"summarize\": Modality.TextLiteral(\n",
        "    \"yes\",\n",
        "    \"no\",\n",
        "    \"true\",\n",
        "    \"True\",\n",
        "    \"false\",\n",
        "    \"False\",\n",
        "    \"1\",\n",
        "    \"0\",\n",
        "    \"<|summarize|>\",\n",
        "    \"<|nosummarize|>\"\n",
        "),\n",
        "```\n",
        "\n",
        "The default can be set as `<|nosummarize|>`:\n",
        "```\n",
        "optional_slots = {\n",
        "    \"decodercontext\": \"\",\n",
        "    \"emotion\": \"<|emo:undefined|>\",\n",
        "    \"itn\": \"<|noitn|>\",\n",
        "    \"timestamp\": \"<|notimestamp|>\",\n",
        "    \"diarize\": \"<|nodiarize|>\",\n",
        "    \"pnc\": \"<|pnc|>\",  \n",
        "    \"summarize\": \"<|nosummarize|>\",\n",
        "}\n",
        "```\n",
        "Then, you'll pass `\"summarize\": true` to the manifest for samples from speech summarization data, where the corresponding `text` will refer to the summary text.\n",
        "\n",
        "```\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": summary, # note that this is now a text summary and not a transcript\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"summarize\": \"true\",\n",
        "}\n",
        "```\n",
        "\n",
        "The default list of special tokens does not have `<|summarize|>` and `<|nosummarize|>` in the vocabulary. So you'll want to build a new tokenizer for the new vocabulary of `spl_tokens`.\n",
        "\n",
        "You can selectively retain token embeddings for the matched tokens, or simply reinitialize all token embeddings.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MhTpxSXJE_R6"
      },
      "source": [
        "## 5. Starting from Canary-flash checkpoint\n",
        "\n",
        "For any of the above scenarios, you may choose to intialize the model from one of the public Canary-flash checkpoints. In the previous section we saw a working example of fine-tuning from a Canary-flash checkpoint. Here we see how we can customize the arguments.\n",
        "\n",
        "We use the `include` and `exclude` paramaters to appropriately restore or drop certain weights, in case there is a difference in tokenizer or model architecture.\n",
        "\n",
        "\n",
        "  (i) Initialize all the parameters\n",
        "\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "  ```\n",
        "\n",
        "  (ii) Initialize just the encoder:\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "      include: [\"encoder\"]\n",
        "  ```\n",
        "\n",
        "  (iii) Initialize encoder and decoder but not the token embeddings (relevant for scenarios that use a different tokenizer):\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "      exclude: [\"transf_decoder._embedding.token_embedding\", \"log_softmax.mlp.layer0\"]\n",
        "\n",
        "  ```\n",
        "\n",
        "  (iv) If you wish further customization that cannot be handled with just these arguments, you can modify https://github.com/NVIDIA/NeMo/blob/main/nemo/core/classes/modelPT.py. Specifically, modify the following snippet of code\n",
        "\n",
        "  ```\n",
        "  dict_to_load = {}\n",
        "  for k, v in state_dict.items():\n",
        "      should_add = False\n",
        "      # if any string in include is present, should add\n",
        "      for p in include:\n",
        "          if p in k:\n",
        "              should_add = True\n",
        "              break\n",
        "      # except for if any string from exclude is present\n",
        "      for e in exclude:\n",
        "          if e in k:\n",
        "              excluded_param_names.append(k)\n",
        "              should_add = False\n",
        "              break\n",
        "      if should_add:\n",
        "          dict_to_load[k] = v\n",
        "  ```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uKCijB1ijs6_"
      },
      "source": [
        "# Practitioner's tips"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mWUkwjPfFk_J"
      },
      "source": [
        "## Starting from a pre-trained checkpoint\n",
        "\n",
        "In our experience working with Canary, we noticed that starting from a pre-trained speech encoder, greatly helps convergence. Especially for larger models (1B+ params) initializing from a pretrained encoder may even be required to stabilize the training.\n",
        "\n",
        "Canary-180M-Flash 17-layer fastconformer encoder was initialized from a 17-layer fastconformer encoder of a transducer speech recognition model ([model](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_multilingual_fastconformer_hybrid_large_pc_blend_eu/files), [config](https://github.com/NVIDIA/NeMo/blob/main/examples/asr/conf/fastconformer/fast-conformer_transducer_bpe.yaml#L29)). The 4-layer transformer decoder was initialized from scratch.\n",
        "\n",
        "Canary-1B-Flash has 32-layer fastconformer encoder. The first 24 layers were initialized from a 24-layer fastconfromer encoder of a transducer speech recognition model and the rest were randomly initalized. This 24-layer model was training internally with this [config](https://github.com/NVIDIA/NeMo/blob/main/examples/asr/conf/fastconformer/fast-conformer_transducer_bpe.yaml#L31)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jfFcQv0Pj1Tj"
      },
      "source": [
        "## Training Canary for multiple tasks\n",
        "\n",
        "We have seen that Canary-Flash models support multiple capabilities -- speech recognition in four languages (ASR), speech to text translation (AST)for six language pairs, timestamp (TS) prediction in four languages. Canary-Flash models are also optimized to be robust to background noise (NR) and hallucination (HR).\n",
        "\n",
        "These capabilties were achieved over three stages of training:\n",
        "* **Stage 1**: ASR+AST\n",
        "* **Stage 2**: ASR+AST+HR+NR\n",
        "* **Stage 3**: ASR+AST+HR+NR+TS\n",
        "\n",
        "At each stage, we add new capability to the model and at the same time we continue supervised training for previously learned capabilities. This is essential for the model to learn without forgetting.\n",
        "\n",
        "So, whenever you perform Canary-style training, irrespective of whether or not you start from a Canary-Flash checkpoint, make sure that the training data mix includes supervision for all the capabilities (tasks and languages) that you wish the final model to learn and retain.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tVmcFlA5Ftpu"
      },
      "source": [
        "## Training efficiency with 2-D bucketing and OOMptimizer\n",
        "\n",
        "Canary-Flash training is also optimized for optimal GPU utilization. 2-D bucketing and OOMptimizer are the two key components of for optimal GPU utilization, handled by the config as shown below.\n",
        "```\n",
        "model:\n",
        "  train_ds:\n",
        "    use_bucketing: true\n",
        "    bucket_duration_bins: [[3.79,27],[3.79,65],[4.8,34],[4.8,66],[5.736,39],[5.736,73],[6.42,44],[6.42,79],[7.182,47],[7.182,87],[8.107,52],[8.107,100],[8.78,60],[8.78,111],[9.62,66],[9.62,115],[10.47,71],[10.47,127],[11.14,76],[11.14,139],[11.8,78],[11.8,139],[12.47,82],[12.47,150],[13.02,88],[13.02,160],[13.55,92],[13.55,160],[14.1,94],[14.1,168],[14.64,97],[14.64,169],[15.15,101],[15.15,175],[15.63,102],[15.63,170],[16.09,104],[16.09,180],[16.63,107],[16.63,186],[17.17,109],[17.17,184],[17.71,113],[17.71,206],[18.18,116],[18.18,208],[18.67,119],[18.67,209],[19.13,123],[19.13,210],[19.61,125],[19.61,226],[20.18,126],[20.18,232],[32.467,184],[32.467,321],[36.567,243],[36.567,398],[40.0,272],[40.0,437]]\n",
        "    bucket_batch_size: [334,314,264,248,221,214,196,190,174,169,155,146,142,134,126,123,116,112,106,103,103,95,95,92,92,89,89,86,84,82,80,78,78,76,76,74,74,72,72,68,68,66,66,64,64,62,62,60,60,58,58,56,56,54,33,32,29,28,26,25]\n",
        "```\n",
        "\n",
        "See these parameters for `canary-180m-flash` model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UiAbyTiyTEXt"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LP2E0SgvSvI1"
      },
      "outputs": [],
      "source": [
        "print('bucket_duration_bins: \\n', canary_model._cfg['train_ds']['bucket_duration_bins'])\n",
        "print('bucket_batch_size: \\n', canary_model._cfg['train_ds']['bucket_batch_size'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l8DJDwyUS3q4"
      },
      "source": [
        "Simply put, these tools set the optimal batch statistics after considering the distribution of lengths of input audio, lengths of decoder outputs (decoder prompt and tokenized transcript), and model size. Bucketing (`bucket_duration_bins`)ensures that a training batch does not have samples of uneven lengths, as that would lead to wasteful usage of memory by the `<pad>` tokens. OOMptimizer sets batchsizes (`bucket_batch_sizes`) for each bucket ensuring that the training utilizes optimal GPU memory while not running into OOM errors.\n",
        "\n",
        "\n",
        "\n",
        "An alternative, if you don't wish to use bucketing, is to set the batchsize explicitly.\n",
        "```\n",
        "model:\n",
        "  train_ds:\n",
        "    use_bucketing: false\n",
        "    batch_size: 32\n",
        "```\n",
        "\n",
        "Next we add pointers to the script that compute `bucket_duration_bins` and `bucket_batch_sizes`. You will need config for your data, config for your model, and paths to tokenizers.\n",
        "\n",
        "Let's say `$NEMO_DIR` is path to the installed NeMo library.\n",
        "\n",
        "First step is to estimate 2D buckets bins using the data config and tokenizers. It takes as arguments, number of buckets, number of sub-buckets (2D in our case), number of utterances used to estimate the bins, lowest and highest duration in seconds, and arguments related to dataset manifest, tokenizers, and prompt format.\n",
        "\n",
        "```\n",
        "python $NEMO_DIR/scripts/speech_recognition/estimate_duration_bins_2d.py \\\n",
        "    -b 30 \\\n",
        "    -s 2 \\\n",
        "    -n 100000 \\\n",
        "    -l 0.5 -u 40.0 \\\n",
        "    -t $tokenizer_model1 $tokenizer_model2 $tokenizer_model3 \\\n",
        "    -a $lang1 $lang2 $lang3 \\\n",
        "    --lang-field target_lang \\\n",
        "    --text-field answer \\\n",
        "    -f canary2 \\\n",
        "    -p \"[{'role':'user','slots':{'source_lang':'en','target_lang':'en','pnc':'yes','decodercontext':'','emotion':'<|emo:undefined|>','itn':'yes','diarize':'yes','timestamp':'yes'}}]\" \\\n",
        "    $dataset_config\n",
        "```\n",
        "\n",
        "The next step is to obtain `bucket_batch_sizes` using the estimated `bucket_duration_bins` and model config.\n",
        "```\n",
        "BUCKETS=$bucket_duration_bins\n",
        "\n",
        "python $NEMO_DIR/scripts/speech_recognition/oomptimizer.py \\\n",
        "    -m nemo.collections.asr.models.EncDecMultiTaskModel\\\n",
        "    -c $config \\\n",
        "    --no-ddp \\\n",
        "    -b \"$BUCKETS\"\n",
        "\n",
        "```\n",
        "\n",
        "Then you'd update the training config accordingly and launch a training job as shown before.\n",
        "\n",
        "If you are interested to learn more about these tools, we discuss illustrative examples, technical details, and report efficiency gains in [Zelasko et al.](https://arxiv.org/abs/2503.05931).\n",
        "\n",
        "Refer to documentation on [2-D bucketing](https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/asr/datasets.html#d-bucketing) and [OOMptimizer](https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/asr/datasets.html#pushing-gpu-utilization-to-the-limits-with-bucketing-and-oomptimizer) for more details."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "75eaOh_LT55a"
      },
      "source": [
        "## Masking loss for prompt tokens\n",
        "\n",
        "The config has `use_loss_mask_for_prompt` parameter which decides whether or not the training objective includes loss for the decoder prompt tokens.\n",
        "\n",
        "We noticed that masking prompt loss tokens led to a better performing `canary-180m-flash` model, where as it did not make any noticeable difference for `canary-1b-flash`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4ArQlMTeUhEO"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FXMJX8lXU1WP"
      },
      "outputs": [],
      "source": [
        "print('prompt loss masking for canary-180m-flash: \\n', canary_model._cfg['use_loss_mask_for_prompt'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "umo2f6yI4Y--"
      },
      "source": [
        "# Follow-up reading material and tutorials\n",
        "\n",
        "1. [SentencePiece](https://arxiv.org/abs/1808.06226) and [concatenated](https://arxiv.org/abs/2306.08753) tokenizer: To learn more about the tokenization process.\n",
        "\n",
        "\n",
        "2. [Tutorial on prompt formatter](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Prompt%20Formatter%20Tutorial.ipynb): To learn more about prompt formatter.\n",
        "\n",
        "2. [Tutorial on multi-task adapters](https://github.com/NVIDIA/NeMo/blob/main/tutorials/asr/asr_adapters/Multi_Task_Adapters.ipynb): If you wish to explore adaptation of `Canary-flash` checkpoints using adapters."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "ame",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
